How to use iloc[] function In Python Pandas
This function is used to get the first column using slice operator. for the rows we extract all of them, for columns specify the index for first column.
Syntax :
dataframe.iloc[:, 0]
where. dataframe is the input dataframe
The slice operation will be like:
[row_start:row_end , column_start, column_end]
where,
- row_start refers start row with 0 position as index
- row_end refers last row with n th position as index
- column_start refers start column with 0 position as index
- column_end refers last column with n th position as index
The following alternative can also be employed.
Syntax :
dataframe.iloc[:, :1]
where. dataframe is the input dataframe. Both of these will return the dataframe datatype.
Example: Python program to get the first column by using above approaches
Python3
# import pandas module import pandas as pd # create dataframe with 3 columns data = pd.DataFrame({ "id" : [ 7058 , 7059 , 7072 , 7054 ], "name" : [ 'sravan' , 'jyothika' , 'harsha' , 'ramya' ], "subjects" : [ 'java' , 'python' , 'html/php' , 'php/js' ] } ) # display dataframe print (data) print ( "--------------" ) # get first column by returning series print (data.iloc[:, 0 ]) print ( "--------------" ) # get first column by returning dataframe print (data.iloc[:, : 1 ]) |
Output:
How to Get First Column of Pandas DataFrame?
In this article, we will discuss how to get the first column of the pandas dataframe in Python programming language.
Contact Us